package settingapp

import (
	"gitee.com/captials-team/ubdframe/src/apps"
	httpController "gitee.com/captials-team/ubdframe/src/apps/settingapp/controllers/http"
	"gitee.com/captials-team/ubdframe/src/apps/settingapp/docs"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/pkg/gin_http"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"gitee.com/captials-team/ubdframe/src/pkg/uber_help"
	"github.com/gin-gonic/gin"
	"go.uber.org/dig"
)

type ApiServer struct {
	*apps.ApiServer

	di   *dig.Container
	conf *configstc.SettingAppConfig

	gin_http.AuthOption           //认证相关选项配置
	gin_http.SwaggerOption        //swagger相关选项配置
	gin_http.PProfOption          //pprof选项配置
	gin_http.OperateLogOption     //操作日志
	gin_http.AuthExtendInfoOption //认证扩展信息选项配置
	gin_http.AccreditOption       //授权选项
}

func (s *ApiServer) Name() string {
	return "setting_api"
}

func (s *ApiServer) InitRouter() {
	s.Engine().GET("ping", gin_http.PingHandler)
	s.InitRouterForGin(s.Engine())
}

func (s *ApiServer) router(g gin.IRouter) {
	g.Use(
		gin_http.PanicHandler,
		gin_http.QPSLimiterHandler(10, 10),
	)
	authGroup := g.Group("", s.OptAuthHandler(), s.OptAccreditHandler())

	common.ErrPanic(s.di.Invoke(func(ctr interfaces.ItfSettingController) {
		authGroup.POST("/setting/get", ctr.GetSetting) //获取单个配置
		authGroup.POST("/setting/put", ctr.PutSetting) //保存单个配置

		authGroup.POST("/setting/multi/get", ctr.GetMultiSetting) //获取多个配置
		authGroup.POST("/setting/multi/put", ctr.PutMultiSetting) //保存多个配置
	}))

	//对外的获取配置
	common.ErrPanic(s.di.Invoke(func(ctr interfaces.ItfSettingController) {
		//g.POST(  "/setting/get", ctr.GetSetting)
		//g.POST(  "/setting/multi/get", ctr.GetMultiSetting)
	}))
}

func (s *ApiServer) InitRouterForGin(engine *gin.Engine) {
	var g = engine.Group("")
	if len(s.conf.RoutePrefix) > 0 {
		g = engine.Group(s.conf.RoutePrefix)
	}

	//注册swagger
	s.SwaggerRouter(g)

	//注册pprof
	s.PProfRouter(engine)

	s.router(g)

	return
}

func (s *ApiServer) Start() error {
	if !s.Module() {
		s.InitRouter()
	}
	return s.ApiServer.Start()
}

func (s *ApiServer) Stop() error {
	return s.ApiServer.Stop()
}

func NewApiServer(di *dig.Container, conf *configstc.SettingAppConfig, logger v1log.ILog) *ApiServer {
	common.ErrPanic(di.Provide(httpController.NewSettingController, dig.As(new(interfaces.ItfSettingController))), uber_help.ErrAlreadyProvided)

	docs.SwaggerInfosettingservice.Host = conf.ApiServer.HostAddr() + conf.RoutePrefix

	s := &ApiServer{
		di:   di,
		conf: conf,
		SwaggerOption: gin_http.SwaggerOption{
			Enable:  conf.DocsEnable,
			Name:    docs.SwaggerInfosettingservice.InstanceName(),
			Swagger: docs.SwaggerInfosettingservice,
		},
		PProfOption: gin_http.PProfOption{
			Enable: conf.PProfEnable,
		},
		ApiServer: apps.NewApiServer(gin.Default(), conf.ApiServer),
	}

	s.ApiServer.WithCors()

	return s
}
